package com.gombe.credit.app.ui.activity

import android.os.Handler
import android.os.Looper
import android.view.View
import androidx.activity.result.contract.ActivityResultContracts
import com.gombe.credit.app.R
import com.gombe.credit.app.common.CommonActivity
import com.gombe.credit.app.configs.GombeCreditApiPath
import com.gombe.credit.app.configs.GombeCreditApiUrl
import com.gombe.credit.app.configs.GombeCreditApiUrl.addCommonParams
import com.gombe.credit.app.databinding.ActGombeCreditUserSettingPageBinding
import com.gombe.credit.app.event.GombeCreditEventPointType
import com.gombe.credit.app.request.IHttpCallback
import com.gombe.credit.app.ui.dialog.DialogGombeCreditUserDataDelete
import com.gombe.credit.app.utils.GombeCreditTitleBarUtil
import com.gombe.credit.app.utils.helper.GombeCreditConfigsHelper
import com.gombe.credit.app.utils.helper.GombeCreditUpdateHelper
import com.gombe.credit.app.utils.shared.GombeCreditSharedHelper
import com.gombe.credit.lib.adapter.GombeCreditOnSingleClickListener
import org.json.JSONObject

/**
 * GombeCredit
 * @Author wwdeng
 * @CreateTime: 2024/11/27 16:16
 * @Annotation：设置
 */
class ActGombeCreditUserSetting: CommonActivity() {
    lateinit var binding: ActGombeCreditUserSettingPageBinding
    private var deleteDataAfterDate = ""

    private var updateHelper: GombeCreditUpdateHelper? = null
    private val updateLauncher = registerForActivityResult(ActivityResultContracts.StartIntentSenderForResult()) { result ->
        if (result.resultCode == RESULT_OK) {
            //更新成功

        } else {

        }
    }
    override fun takeGombeCreditRootView(): View {
        binding = ActGombeCreditUserSettingPageBinding.inflate(layoutInflater)
        return binding.root
    }

    override fun initGombeCreditView() {
        setGombeCreditTitleBarVisibility(View.VISIBLE)
        setGombeCreditTextTitle(getString(R.string.gombe_credit_user_center_setting))
        setGombeCreditTextTitleColor(getColor(R.color.black))
        setGombeCreditRightBtnRes(R.mipmap.gombe_credit_image_customer_black_icon)
        setGombeCreditBackBtnRes(R.mipmap.gombe_credit_image_back_black_icon)
        GombeCreditTitleBarUtil.setStatusBarLightMode(this, true)
        setGombeCreditRootParentBackgroundColor(getColor(R.color.white))
    }

    override fun initGombeCreditListener() {
        //客服
        rootViewBinding.rootCustomer.setOnClickListener(object : GombeCreditOnSingleClickListener(){
            override fun onSingleClick(v: View?) {
                showCustomerDialog("Setting Page")
                addEventPointRequestAction(GombeCreditEventPointType.GOMBECREDIT_TRACK_CLICK.CUSTOMER,"Setting Page")
            }
        })

        //更新版本
        binding.buttonUpdate.setOnClickListener {
            //是否有新版本
            val isUpdate = GombeCreditConfigsHelper.isGombeCreditUpdate()
            if (!isUpdate){
                showGombeCreditToast(getString(R.string.gombe_credit_update_no_version))
                return@setOnClickListener
            }
            if (updateHelper == null){
                updateHelper = GombeCreditUpdateHelper(activity = this, forceUpdate = false, updateLauncher)
            }
            updateHelper?.checkAndStartUpdate { }
        }

        //清空用户数据
        binding.buttonDeleteData.setOnClickListener(object : GombeCreditOnSingleClickListener(){
            override fun onSingleClick(v: View?) {
                addEventPointRequestAction(GombeCreditEventPointType.GOMBECREDIT_TRACK_CLICK.USER_DATA_CLEAR)
                showUserClearDataDialog()
            }
        })

        //退出登录
        binding.buttonSignOut.setOnClickListener(object : GombeCreditOnSingleClickListener(){
            override fun onSingleClick(v: View?) {
                addEventPointRequestAction(GombeCreditEventPointType.GOMBECREDIT_TRACK_CLICK.USER_LOGINOUT)
                //退出登录，需要移除用户保存的信息
                GombeCreditSharedHelper.onGombeCreditLoginOut()
                Handler(Looper.getMainLooper()).postDelayed({
                    onIntent(ActGombeCreditUserLogin::class.java)
                },300)
            }
        })
    }

    override fun takeGombeCreditData() {
        //获取版本名称
        val packageInfo = packageManager.getPackageInfo(this.packageName, 0)
        binding.textAppVersion.text = String.format(getString(R.string.gombe_credit_user_setting_version),packageInfo.versionName)

        //是否有新版本
        val isUpdate = GombeCreditConfigsHelper.isGombeCreditUpdate()
        if (isUpdate){
            binding.updateViewPoint.visibility = View.VISIBLE
        } else {
            binding.updateViewPoint.visibility = View.GONE
        }

        binding.buttonDeleteData.visibility = View.INVISIBLE
        //需要判断是否需要显示删除用户数据按钮
        submitGombeCreditUserDataDeleteAction(true)
    }

    override fun onResume() {
        super.onResume()
        updateHelper?.resumeIfInProgress()
    }

    /**
     * 清空用户数据dialog
     */
    private fun showUserClearDataDialog(){
        val clearDialog = DialogGombeCreditUserDataDelete(this,"Setting Page",object : DialogGombeCreditUserDataDelete.IDialogCallback{
            override fun onUserDataClearConfirmClick() {
                submitGombeCreditUserDataDeleteAction(false)
            }
        })
        clearDialog.setCancelable(true)
        clearDialog.setCanceledOnTouchOutside(true)
        clearDialog.show()
        clearDialog.showGombeCreditUserDataDeleteInfo(GombeCreditConfigsHelper.takeGombeCreditDeletePersonalDataDesc(),deleteDataAfterDate)
    }

    /**
     * 清除用户数据 或 获取是否显示删除数据按钮
     */
    private fun submitGombeCreditUserDataDeleteAction(isShowDeleteButton: Boolean){
        showGombeCreditLoading()
        val httpUrl = GombeCreditApiUrl.takeRequestUrl()
        val params = JSONObject().addCommonParams().apply {
            put("path", GombeCreditApiPath.GOMBECREDIT_PATH.GOMBECREDIT_API_USER_DATA_CLEAR_PATH)
        }
        if (isShowDeleteButton){
            params.put("type","GET")
        } else {
            params.put("type","DROP")
        }
        doPostAction(httpUrl, params, object : IHttpCallback {
            override fun onRequestSuccess(data: JSONObject) {
                if (isShowDeleteButton){
                    val obj = data.optJSONObject("obj")
                    if (obj != null && obj.has("showDropButton") && obj.optString("showDropButton") == "YES"){
                        binding.buttonDeleteData.visibility = View.VISIBLE
                        deleteDataAfterDate = obj.optString("againDate")
                    } else {
                        binding.buttonDeleteData.visibility = View.INVISIBLE
                    }
                } else {
                    hideGombeCreditLoading()
                    //退出登录，需要移除用户保存的信息
                    GombeCreditSharedHelper.onGombeCreditLoginOut()
                    onIntent(ActGombeCreditUserLogin::class.java)
                }
            }
            override fun onRequestError(error: JSONObject) {
                showGombeCreditToast(error.optString("errorMsg"))
            }
            override fun onRequestFinish() {
                hideGombeCreditLoading()
            }
        })
    }

    override fun onStart() {
        super.onStart()
        addEventPointRequestAction(GombeCreditEventPointType.GOMBECREDIT_TRACK_PAGE.USER_SETTING_START)
    }

    override fun onDestroy() {
        super.onDestroy()
        addEventPointRequestAction(GombeCreditEventPointType.GOMBECREDIT_TRACK_PAGE.USER_SETTING_END)
    }
}